package com.hptpd.questionnairesurvey.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.hptpd.questionnairesurvey.assets.Constant;
import com.hptpd.questionnairesurvey.assets.WeiXinApiUrl;
import com.hptpd.questionnairesurvey.component.Result;
import com.hptpd.questionnairesurvey.domain.Department;
import com.hptpd.questionnairesurvey.domain.User;
import com.hptpd.questionnairesurvey.repository.DepartmentRep;
import com.hptpd.questionnairesurvey.repository.UserRep;
import com.hptpd.questionnairesurvey.service.IQyWeiXinApiService;
import com.hptpd.questionnairesurvey.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* Date: 2019-04-23 17:04
 * \*
 * \* Description:
 * \
 *
 * @author longwei
 */
@Service("iQyWeiXinApiService")
public class QyWeiXinApiServiceImpl implements IQyWeiXinApiService {
    private Logger logger = LoggerFactory.getLogger(QyWeiXinApiServiceImpl.class);

    @Value("${weixin.company.corpsecret}")
    private String weixinCompanyCorpsecret;

    @Value("${weixin.company.corpid}")
    private String weixinCompanyCorpid;

    @Resource(name="departmentRep")
    private DepartmentRep departmentRep;

    @Resource(name="userRep")
    private UserRep userRep;

    @Override
    public Result updateCompanyAccessToken() {
        JSONObject jsonObject = null;
        try {
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("corpid", weixinCompanyCorpid);
            paramMap.put("corpsecret", weixinCompanyCorpsecret);
            jsonObject = HttpUtil.doGet(WeiXinApiUrl.GET_COMPANY_ACCESSTOKEN, paramMap);
            logger.debug("updateCompanyAccessToken data: {}", jsonObject);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (null != jsonObject && Constant.REQUEST_SUCCESS_CODE.equals(jsonObject.getInteger(WeiXinApiUrl.ERRCODE_KEY))) {
            Constant.WEIXIN_COMPANY_ACCESSTOKEN = jsonObject.getString(WeiXinApiUrl.ACCESS_TOKEN_KEY);
        }
//        if (null == jsonObject || !Constant.REQUEST_SUCCESS_CODE.equals(jsonObject.getInteger(WeiXinApiUrl.ERRCODE_KEY))) {
//            return updateCompanyAccessToken();
//        }
        return Result.ok(jsonObject);
    }

    @Override
    public String getCompanyAccessToken() {
        if (Constant.WEIXIN_COMPANY_ACCESSTOKEN.trim().isEmpty()) {
            this.updateCompanyAccessToken();
        }
        return Constant.WEIXIN_COMPANY_ACCESSTOKEN;
    }

    @Override
    public String useridToOpenid(@NotNull String userId) {
        if (userId.isEmpty()) {
            return null;
        }
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("userid", userId);
        JSONObject jsonObj;
        try {
            jsonObj = HttpUtil.doPost(WeiXinApiUrl.POST_USERID_2_OPENID, paramMap);
            logger.debug("useridToOpenid data: {}", jsonObj);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        if (!Constant.REQUEST_SUCCESS_CODE.equals(jsonObj.getInteger(WeiXinApiUrl.ERRCODE_KEY))) {
            return null;
        }
        return jsonObj.getString("openid");
    }

    @Override
    public String openidToUserid(@NotNull String openId) {
        if (openId.isEmpty()) {
            return null;
        }
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("openId", openId);
        JSONObject jsonObj;
        try {
            jsonObj = HttpUtil.doPost(WeiXinApiUrl.POST_OPENID_2_USERID, paramMap);
            logger.debug("openidToUserid data: {}", jsonObj);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        if (!Constant.REQUEST_SUCCESS_CODE.equals(jsonObj.getInteger(WeiXinApiUrl.ERRCODE_KEY))) {
            return null;
        }
        return jsonObj.getString("userid");
    }

    @Override
    public Result updateCompanyUserAndDepartment() {
        JSONArray departmentJsonArr = this.getCompanyDepartmentList();
        if (null == departmentJsonArr) {
            return Result.updatedDataFailed();
        }
        for (Object o : departmentJsonArr) {
            JSONObject jsonObject = (JSONObject) o;
            Department department = new Department();
            Integer parentId = jsonObject.getInteger("parentid");
            if (0 != parentId) {
                Department parentDepartment = new Department();
                parentDepartment.setId(parentId);
                department.setParentDepartment(parentDepartment);
            } else {
                department.setParentDepartment(null);
            }
            department.setId(jsonObject.getInteger("id"));
            department.setName(jsonObject.getString("name"));
            department.setSort(jsonObject.getLong("order"));
            departmentRep.saveAndFlush(department);
        }
        JSONArray userJsonArr = this.getCompanyUserList();
        if (null == userJsonArr) {
            return Result.updatedDataFailed();
        }
        for (Object o : userJsonArr) {
            JSONObject jsonObject = (JSONObject) o;
            User user = new User();
            JSONArray jsonArray = jsonObject.getJSONArray("department");
            if (jsonArray.isEmpty()) {
                user.setDepartment(null);
            } else {
                Department department = new Department();
                department.setId((Integer)jsonArray.get(0));
                user.setDepartment(department);
            }
            user.setRealName(jsonObject.getString("name"));
            user.setPhone(jsonObject.getString("userid"));
            userRep.save(user);
        }
        return Result.ok();
    }

    private JSONArray getCompanyUserList() {
        JSONObject jsonObj;
        try {
            jsonObj = HttpUtil.doGet(WeiXinApiUrl.GET_CONMPANY_USERLIST + this.getCompanyAccessToken() + "&department_id=1&fetch_child=1");
            logger.debug("getCompanyUserList data: {}", jsonObj);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        if (!Constant.REQUEST_SUCCESS_CODE.equals(jsonObj.getInteger(WeiXinApiUrl.ERRCODE_KEY))) {
            return null;
        }
        return jsonObj.getJSONArray("userlist");
    }

    private JSONArray getCompanyDepartmentList() {
        JSONObject jsonObj;
        try {
            jsonObj = HttpUtil.doGet(WeiXinApiUrl.GET_CONMPANY_DEPARTMENTLIST + this.getCompanyAccessToken() + "&id=1");
            logger.debug("getCompanyDepartmentList data: {}", jsonObj);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        if (!Constant.REQUEST_SUCCESS_CODE.equals(jsonObj.getInteger(WeiXinApiUrl.ERRCODE_KEY))) {
            return null;
        }
        return jsonObj.getJSONArray("department");
    }
}
